import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/data/device_list_entity.dart';
import 'package:mziot/app/data/group_down_entity.dart';
import 'package:mziot/app/data/scene_list_entity.dart';
import 'package:mziot/app/modules/devices/controllers/choose_scene_controller.dart';
import 'package:mziot/generated/assets.dart';
import 'package:mziot/generated/locales.g.dart';

class ChoseSceneView extends GetView {
  ChooseSceneController controller = ChooseSceneController();
  final bool isGroup;
  final List<GroupDownEntity>? groupList;
  final List<SceneListEntity>? sceneList;
  final List<DeviceListList>? deviceList;
  final ValueChanged<dynamic> valueChange;
  final isMutile;

  ChoseSceneView(this.isGroup, this.groupList, this.sceneList, this.deviceList, this.valueChange,
      {this.isMutile = false}) {
    controller.isGroup = isGroup;
    controller.groupList.value = groupList ?? [];
    controller.sceneList.value = sceneList ?? [];
    controller.deviceList.value = deviceList ?? [];
    controller.isMutile = isMutile;
    controller.checkSelected();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black.withAlpha(60),
      child: Stack(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              Get.back();
            },
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              color: Colors.white,
              height: 400,
              child: Column(
                children: [
                  _topView,
                  Expanded(child: _sceneList),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  get _topView {
    return Container(
      height: 40,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Text(
              isGroup
                  ? controller.deviceList.isNotEmpty
                      ? LocaleKeys.devices_choose_device_title.tr
                      : LocaleKeys.devices_choose_scene_title.tr
                  : LocaleKeys.add_devices_choose_group_title.tr,
              style: MFont.semi_Bold15.apply(color: MColor.xFF333333),
              textAlign: TextAlign.center,
            ),
          ),
          IconButton(
            onPressed: () => Get.back(),
            padding: EdgeInsets.zero,
            icon: Icon(
              Icons.close,
              size: 16,
            ),
          ),
        ],
      ),
    );
  }

  get _sceneList {
    final groupCount = groupList?.length ?? 0;
    final sceneCount = sceneList?.length ?? 0;
    final deviceCount = deviceList?.length ?? 0;

    return SafeArea(
      top: false,
      child: Column(
        children: [
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.zero,
              itemCount: isGroup
                  ? deviceCount > 0
                      ? deviceCount
                      : sceneCount
                  : groupCount,
              itemBuilder: (ctx, index) {
                var nameText = '';
                var startTime = '';
                var endTime = '';
                if (isGroup && sceneCount > 0) {
                  nameText = controller.sceneList.value[index].sceneName ?? '';
                  DateFormat format = DateFormat("MM-dd-yyyy HH:mm:ss");

                  final start = format.parse(controller.sceneList.value[index].startTime ?? '');
                  final end = format.parse(controller.sceneList.value[index].endTime ?? '');
                  startTime = formatDate(start, [mm, '-', dd, '-', yyyy]);
                  endTime = formatDate(end, [mm, '-', dd, '-', yyyy]);
                } else if (isGroup && deviceCount > 0) {
                  nameText = controller.deviceList.value[index].deviceName ?? '';
                } else {
                  nameText = controller.groupList.value[index].groupName ?? '';
                }

                return GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    controller.selectedAction(index);
                  },
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 12),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height: 24),
                                Text(
                                  nameText,
                                  style: MFont.regular13.apply(color: MColor.xFF333333),
                                  textAlign: TextAlign.start,
                                ),
                                if (isGroup && deviceList!.isEmpty) ...{
                                  Container(
                                    child: Text(
                                      '$startTime ~ $endTime',
                                      style: MFont.regular13.apply(color: MColor.xFF999999),
                                    ),
                                    padding: EdgeInsets.only(top: 8),
                                  ),
                                },
                                SizedBox(height: 24),
                              ],
                            ),
                            if (!isGroup) ...{
                              SizedBox(width: 24),
                              Image.asset(
                                Assets.imagesDeviceGroupIcon,
                                width: 20,
                                height: 20,
                              ),
                              SizedBox(width: 4),
                              Text(
                                'x${controller.groupList.value[index].deviceNum ?? 0}',
                                style: MFont.regular11.apply(color: MColor.xFF999999),
                              ),
                            },
                            Spacer(),
                            Obx(() {
                              var selected = false;
                              if (isGroup && sceneCount > 0) {
                                selected = controller.sceneList[index].isSelected.value;
                              } else if (isGroup) {
                                selected = controller.deviceList[index].isSelected.value;
                              } else {
                                selected = controller.groupList[index].isSelected.value;
                              }

                              return Container(
                                padding: EdgeInsets.all(5),
                                decoration: BoxDecoration(
                                  color: selected ? MColor.skin : MColor.xFFEEEEEE,
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                child: Icon(
                                  Icons.check,
                                  size: 10,
                                  color: selected ? Colors.white : MColor.xFFEEEEEE,
                                ),
                              );
                            }),
                          ],
                        ),
                      ),
                      Divider(
                        color: MColor.xFFCCCCCC,
                        height: 0.5,
                        endIndent: 12,
                        indent: 12,
                      ),
                    ],
                  ),
                );
              },
            ),
          ),
          _addBottomView,
        ],
      ),
    );
  }

  get _addBottomView {
    return Container(
      width: double.infinity,
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: SafeArea(
        top: false,
        child: Container(
          child: TextButton(
            style: ButtonStyle(
              shape: MaterialStateProperty.all(StadiumBorder()),
              backgroundColor: MaterialStateProperty.all(MColor.skin),
            ),
            onPressed: () {
              if (controller.isMutile && controller.groupList.isNotEmpty) {
                valueChange(controller.groups);
              } else if (controller.isMutile && controller.sceneList.isNotEmpty) {
                valueChange(controller.scenes);
              } else if (controller.isMutile && controller.deviceList.isNotEmpty) {
                valueChange(controller.devices);
              } else {
                valueChange(controller.selectModel);
              }
              Get.back();
            },
            child: Text(
              LocaleKeys.public_ok.tr,
              style: MFont.regular15.apply(color: MColor.xFFEEEEEE),
            ),
          ),
        ),
      ),
    );
  }
}
